package com.njh.tools.base;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.njh.tools.R;
import com.njh.tools.api.manager.ApiException;
import com.njh.tools.base.util.TUtil;
import com.njh.tools.common.ToastUtils;
import com.njh.tools.common.string.StringUtils;
import com.njh.tools.config.tconstant.Constants;
import com.trello.rxlifecycle.FragmentEvent;

import java.util.concurrent.TimeUnit;

import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import rx.Observable;

/**
 * Created by niejiahuan on 2016/5/12.
 * Fragment父类
 */
public abstract class BaseFragment<T extends BasePresenter, E extends BaseModel> extends SwipeBackFragment implements BaseView {

    protected View baseView;
    public T mPresenter;//UI控制层
    public E mModel;//数据操作层
    protected TextView toolbar_header;
    protected Toolbar toolbar;
    protected ProgressDialog mProgressDialog;

    /**
     * 获取布局文件
     *
     * @return
     */
    public abstract int getLayoutId();

    /**
     * 初始化视图操作
     */
    public abstract void initView(View baseView);

    public abstract boolean isSwipeBack();

    public View getView(LayoutInflater inflater, ViewGroup container) {
        if (null == baseView) {
            if (getLayoutId() != 0) {
                baseView = inflater.inflate(getLayoutId(), container, false);
                initCreateView();
            } else {
                throw new RuntimeException(
                        "Class need add LayoutId");
            }
        }

        if (isSwipeBack()) {
            return attachToSwipeBack(baseView);
        } else {
            return baseView;
        }

    }

    public void initCreateView() {
        mPresenter = TUtil.getT(this, 0);
        mModel = TUtil.getT(this, 1);
        this.initPresenter();
        this.initView(baseView);
        if (getActivity() != null) {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setMessage(getResources().getString(R.string.waitting));
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setCancelable(true);
        }
    }

    ;

    /**
     * 简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
     */
    public abstract void initPresenter();

    /**
     * 获取视图依赖的activity
     *
     * @return
     */
    public Activity getBaseActivty() {
        return this.getActivity();
    }

    /**
     * 防抖动，防止快速点击
     *
     * @param observable
     * @param <T>
     * @return
     */
    protected <T extends Object> Observable<T> throttleFirst(Observable<T> observable) {
        return observable.throttleFirst(Constants.WINDOW_DURATION, TimeUnit.MILLISECONDS);
    }

    /**
     * 将事件与生命周期绑定
     *
     * @param observable
     * @return
     */
    protected <T extends Object> Observable<T> bindLife(Observable<T> observable) {
        return observable.compose(this.<T>bindToLifecycle());
    }

    /**
     * 指定事件在哪个生命周期结束
     *
     * @param observable
     * @param event      生命周期
     * @return
     */
    protected <T extends Object> Observable<T> bindUntil(Observable<T> observable, FragmentEvent event) {
        return observable.compose(this.<T>bindUntilEvent(event));
    }

    //    //初始化toolbar
    protected void initToolbar(int title) {
        toolbar = (Toolbar) baseView.findViewById(R.id.toolbar);
        toolbar_header = (TextView) baseView.findViewById(R.id.toolbar_title_tv);
        toolbar.setTitle("");
        toolbar_header.setText(this.getResources().getString(title));
    }
    //    //初始化toolbar
    protected void initToolbar(String title) {
        toolbar = (Toolbar) baseView.findViewById(R.id.toolbar);
        toolbar_header = (TextView) baseView.findViewById(R.id.toolbar_title_tv);
        toolbar.setTitle("");
        toolbar_header.setText(title);
    }
    protected void initToolbarNav(int title) {
        if (title>0){
            initToolbar(title);
        }
        toolbar.setNavigationIcon(R.mipmap.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _mActivity.onBackPressed();
            }
        });

    }

    public void setTextValue(TextView tv, String value) {
        if (!StringUtils.isEmpty(value)) {
            tv.setVisibility(View.VISIBLE);
            tv.setText(value);
        } else {
            tv.setVisibility(View.GONE);
        }
    }

    @Override
    public void showError(Throwable e) {
        hideLoading();
        if (e instanceof ApiException) {
            ToastUtils.showShort(this.getBaseActivty(),((ApiException) e).getMsg());
        } else {
            ToastUtils.showShort(this.getBaseActivty(),R.string.connect_fail);
            LogUtils.wtf(e);
        }
    }

    @Override
    public void showLoading() {
        if (mProgressDialog != null && (!mProgressDialog.isShowing())) {
            mProgressDialog.show();
        }
    }

    @Override
    public void hideLoading() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    /**
     * 打卡或关闭软键盘
     */
    public static void openOrcloseKeybord(Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        //得到InputMethodManager的实例
        if (imm.isActive()) {
            //如果开启
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
            //关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
        }
    }


}
